<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "word".
 *
 * @property int $id
 * @property string $keyword
 * @property int $num
 */
class Word extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'word';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'required'],
            [['id', 'num'], 'integer'],
            [['keyword'], 'string', 'max' => 128],
            [['id'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'keyword' => 'Keyword',
            'num' => 'Num',
        ];
    }
	public static  function string2array($keywords)
    {
    	return preg_split('/\s*,\s*/',trim($keywords),-1,PREG_SPLIT_NO_EMPTY);
    }
    public static  function array2string($keywords)
    {
    	return implode(', ',$keywords);
    }	
    public static function findWordWeights($limit=20)
    {
    	$word_size_level = 5;
    	 
    	$models=Word::find()->orderBy('num desc')->limit($limit)->all();
    	$total=Word::find()->limit($limit)->count();
    	 
    	$stepper=ceil($total/$word_size_level);
    	 
    	$words=array();
    	$counter=1;
    	 
    	if($total>0)
    	{
    		foreach ($models as $model)
    		{
    			$weight=ceil($counter/$stepper)+1;
    			$words[$model->keyword]=$weight;
    			$counter++;
    		}
    		ksort($words);
    	}
    	return $words;
    }
    public static function addWords($words)
    {
    	if(empty($words)) return ;
    	
    	foreach ($words as $keyword)
    	{
    		$aWord = Word::find()->where(['keyword'=>$keyword])->one();
    		$aWordCount = Word::find()->where(['keyword'=>$keyword])->count();
    		
    		if(!$aWordCount)
    		{
    			$word = new Word;
    			$word->keyword = $keyword;
    			$word->num = 1;
    			$word->save();
    		}
    		else 
    		{
    			$aWord->num += 1;
    			$aWord->save();
    		}
    	}
    }
    
    public static function removeWords($words)
    {
    	if(empty($words)) return ;
    	
    	foreach($words as $name)
    	{
    		$aWord= Word::find()->where(['name'=>$name])->one();
    		$aWordCount = Word::find()->where(['name'=>$name])->count();
    		
    		if($aWordCount)
    		{
    			if($aWordCount && $aWord->num<=1)
    			{
    				$aWord->delete();
    			}
    			else 
    			{
    				$aWord->num -= 1;
    				$aWord->save();
    			}
    		}
    	}
    }
    
    public static function updateNum($oldWords,$newWords)
    {
    	if(!empty($oldWords) || !empty($newWords))
    	{
    		$oldWordsArray = self::string2array($oldWords);
    		$newWordsArray = self::string2array($newWords);
    		
    		self::addwords(array_values(array_diff($newWordsArray,$oldWordsArray)));
    		self::removeWords(array_values(array_diff($oldWordsArray,$newWordsArray)));
    	}
    }	
}
